const express = require("express")
const cors = require("cors")
const joi = require("joi")
const { expressjwt } = require("express-jwt")
const {
  userrouter,
  myrouter,
  artistrouter,
  articlerouter,
} = require("./src/router")
const { jwtSecretKey } = require("./src/config")

const app = express()

app.use(express.static("./src/uploads"))
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// 封装res.cc函数简化send
app.use((req, res, next) => {
  res.cc = function (err, status = 1) {
    res.send({ status, message: err instanceof Error ? err.message : err })
  }
  next()
})

// 解析token
app.use(
  expressjwt({ secret: jwtSecretKey, algorithms: ["HS256"] }).unless({
    path: [/^\/api\//],
  })
)

app.use("/api", userrouter)
app.use("/my", myrouter)
app.use("/my/article", artistrouter)
app.use("/my/articles", articlerouter)

app.use(function (err, req, res, next) {
  if (err instanceof joi.ValidationError) return res.cc(err)
  if (err.name === "UnauthorizedError") return res.cc("身份认证失败！")
  res.cc(err)
})

app.listen(3000, () => {
  console.log("server is running")
})
